/*
 *  Copyright 2011-2012 Redia A/S
 * 
 *  This file is part of Redias Android Utilities.
 *
 *  Redias Android Utilities is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Redias Android Utilities is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Redias Android Utilities.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.redia.lib.xmlrpc;

import java.util.Map;

import dk.redia.lib.log.Log;

public class XmlRpcResultUtils {
	
	private static final String logTag = "XmlRpcResultUtils";

	@SuppressWarnings("unchecked")
	public static Map<String, Object> unpackStruct(Object struct) {
		try {
			return (Map<String, Object>)struct;
		} catch (ClassCastException e) {
			Log.w(XmlRpcResultUtils.logTag, "Failed to unpack struct from object of unknown type: " + e.getMessage());
			return null;
		}
	}
	
	public static Map<String, Object> unpackStandardResult(Object result) {
		if (result instanceof Map<?, ?>) {
			@SuppressWarnings("unchecked")
			Map<String, Object> resultMap = (Map<String, Object>)result;
			if (!resultMap.containsKey("result")) {
				Log.w(XmlRpcResultUtils.logTag, "Missing result field in result object");
				return null;
			}
			if (!resultMap.containsKey("message")) {
				Log.w(XmlRpcResultUtils.logTag, "Missing message field in result object");
				return null;
			}
			if (!resultMap.containsKey("data")) {
				Log.w(XmlRpcResultUtils.logTag, "Missing data field in result object");
				return null;
			}
			return resultMap;
		} else {
			Log.w(XmlRpcResultUtils.logTag, "Result is not a standard object");
			return null;
		}
	}

	public static Object[] unpackArray(Object result) {
		try {
			Object[] r = (Object[])result;
			return r;
		} catch (ClassCastException e) {
			Log.w(XmlRpcResultUtils.logTag, "Failed to convert object to array. Dumping actual data structure.");
			XmlRpcResultDumper.dump(result);
			e.printStackTrace();
			return null;
		}
	}
}
